package com.yunhe.common.util;

import com.yunhe.common.model.PageParam;
import com.yunhe.common.option.QueryProperties;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询工具类
 * @author liuronglei
 */
public class QueryUtil {

    public static boolean needPaging(PageParam pageParam) {
        return pageParam != null && (pageParam.getPage() != -1 || pageParam.getSize() != -1);
    }

    public static Sort defaultSort() {
        List<String> sortParam = new ArrayList<>();
        sortParam.add(QueryProperties.sortField);
        return getSort(sortParam);
    }

    public static Sort getSort(List<String> sortParam) {
        if (sortParam == null || sortParam.size() == 0) {
            return null;
        }
        List<Sort.Order> orderList = new ArrayList<>();
        for (String aSortParam : sortParam) {
            if (aSortParam.startsWith(QueryProperties.sortDesc)) {
                orderList.add(new Sort.Order(Sort.Direction.DESC, aSortParam.substring(1)));
            } else {
                orderList.add(new Sort.Order(Sort.Direction.ASC, aSortParam));
            }
        }
        return Sort.by(orderList);
    }

    public static int getPage(PageParam pageParam) {
        int page = pageParam.getPage();
        if (page <= 0) {
            page = QueryProperties.page;
        } else {
            page -= 1;
        }
        return page;
    }

    public static int getSize(PageParam pageParam) {
        int size = pageParam.getSize();
        if (size == -1) {
            size = QueryProperties.size;
        }
        return size;
    }

    public static Pageable getPageRequest(PageParam pageParam) {
        Sort sort = getSort(pageParam.getSort());
        if (sort == null) {
            sort = Sort.unsorted();
        }
        int page = getPage(pageParam);
        int size = getSize(pageParam);
        return PageRequest.of(page, size, sort);
    }

    /**
     * 拼接查询条件字符串
     * @param condition 查询条件列表
     */
    public static String getConditionStr(List<String> condition) {
        StringBuilder result = new StringBuilder();
        if (condition != null && condition.size() > 0) {
            for (int i = 0; i < condition.size(); i++) {
                if (i == 0) {
                    result.append(" where");
                } else {
                    result.append(" and");
                }
                result.append(" ").append(condition.get(i));
            }
        }
        return result.toString();
    }
}
